package examples.socket;

import java.net.*;
import java.io.*;

/**
 *
 * @author prabhat.totoo
 */
public class ConfusedServer {

    public static void main(String args[]) {
        ServerSocket server = null;
        Socket channel = null;
        BufferedReader reader = null;
        PrintStream output = null;
        String clientLine = null;
        StringBuffer serverLine = null;
        boolean bDone = false;
        
        try {
            /* The port number can be just about any number between
            * 1024 and 65,536
            */
            server = new ServerSocket(8313);
            channel = server.accept();
            
            /* In order to create the BufferedReader, we need
            * to wrap the InputStream in an InputStreamReader
            */
            reader = new BufferedReader(new InputStreamReader(channel.getInputStream()));

            /* We are using a PrintStream so that we can use the
            * same methods we always use for printing.
            */
            output = new PrintStream(channel.getOutputStream());
          
            clientLine = reader.readLine();

            while(!bDone && (clientLine != null)) {
                if(clientLine.equalsIgnoreCase("exit")) {
                    bDone = true;
                }
                else {

                    /* In order to reverse the String, we need a
                    * StringBuffer.
                    */
                    serverLine = new StringBuffer(clientLine);
                    serverLine = serverLine.reverse();

                    output.println(serverLine.toString());

                    /* Need to read in the next line */
                    clientLine = reader.readLine();
                }
            }
            output.close();
            reader.close();
            channel.close();
            server.close();
        }
        catch(IOException ioe) {
            System.out.println("I/O Exception occurred while using the server");
            ioe.printStackTrace();
        }

        /* This was added just for fun; it is not necessary */
        System.out.println("I'm melting...");
    }
}